package com.syaccp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syaccp.mapper.CustomerMapper;
import com.syaccp.model.Customer;
import com.syaccp.model.SysDept;
import com.syaccp.model.SysDictData;
import com.syaccp.model.SysUser;
import com.syaccp.request.CustomerAddAndUpdateRequest;
import com.syaccp.request.CustomerSelectRequest;
import com.syaccp.response.CustomerHeaderResponse;
import com.syaccp.response.CustomerImResponse;
import com.syaccp.response.CustomerSelectResponse;
import com.syaccp.service.CustomerService;
import com.syaccp.service.DeptService;
import com.syaccp.service.DictDataService;
import com.syaccp.utils.Result;
import com.syaccp.utils.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Resource
    private DeptService ds;

    @Resource
    private DictDataService dds;


    @Resource
    CustomerMapper customerMapper;


    @Override
    public Result findCustomerHeader(SysUser sysUser) {
        /*QueryWrapper<SysUser> wrapper1 = new QueryWrapper<>();
        wrapper1.select("count(*) as customerCount",
                        "sum(account_count) as accountCount",
                        "sum(balance) as balanceCount",
                        "sum(consume_money) as consumeMoneyCount")
                .eq("service_id",sysUser.getId());*/
        CustomerHeaderResponse customerHeader = this.baseMapper.findCustomerHeader(sysUser);
        // CustomerHeaderResponse map = (CustomerHeaderResponse) maps;
        if (customerHeader==null){
            return Result.error();
        }

        return Result.success(customerHeader);
    }

    /**
     * 通过前台页面传递过来的数据查询客户
     * @param csr
     * @return
     */
    @Override
    public Result findCustomerPage(CustomerSelectRequest csr) {
        SysUser sysUser = SecurityUtil.getLoginUser();
        PageHelper.startPage(csr.getIndex(),5);
        QueryWrapper qw=new QueryWrapper();
        //如果登录人不是超级管理员那么需要本身是客户的对应客服，才能查询
        if (sysUser.getRoleId()!=1){
            qw.eq("service_id",sysUser.getId());
        }
        //查询没有被删除了的
        qw.eq("del_flag",0);
        qw.like(csr.getCustomerName()!=null,"customer_name",csr.getCustomerName());
        //时间段，与时间范围不可同时存在
        if (csr.getTimeBucket()!=null&&csr.getTimeBucket()!=-1){
            int time=csr.getTimeBucket();
            Calendar cal1 = Calendar.getInstance();
            Date date = new Date();
            cal1.setTime(date);
            // 将时分秒,毫秒域清零
            cal1.set(Calendar.HOUR_OF_DAY, 0);
            cal1.set(Calendar.MINUTE, 0);
            cal1.set(Calendar.SECOND, 0);
            cal1.set(Calendar.MILLISECOND, 0);
            //今天
            if (time==0){
                qw.eq("date(create_time)",cal1.getTime());
            }
            //昨天
            if (time==1){
                cal1.set(Calendar.DATE,date.getDate()-1);
                qw.eq("date(create_time)",cal1.getTime());
            }

            //最近7天
            if (time==7){
                cal1.set(Calendar.DATE,date.getDate()-7);
                qw.gt("date(create_time)",cal1.getTime());
            }
            //最近30天
            if (time==30){
                cal1.set(Calendar.DATE,date.getDate()-30);
                qw.gt("date(create_time)",cal1.getTime());
            }
            //本月
            if (time==31){
                //只要设置日期为1号就可以了
                cal1.set(Calendar.DATE,1);
                qw.ge("date(create_time)",cal1.getTime());
            }
            //本年
            if (time==365){
                cal1.set(Calendar.MONTH,0);
                cal1.set(Calendar.DATE,1);
                qw.ge("date(create_time)",cal1.getTime());
            }


        }else {
            //时间范围
            if (csr.getTimeScope()!=null&&csr.getTimeScope().length==2){
                //开始
                qw.ge("create_time",csr.getTimeScope()[0]);
                qw.le("create_time",csr.getTimeScope()[1]);
            }
        }

        //客服公司
        if (csr.getWorkplaceIds()!=null){
            if (csr.getWorkplaceIds().length==1){
                qw.eq("company_id",csr.getWorkplaceIds()[0]);
            }else if (csr.getWorkplaceIds().length==2){
                qw.eq("dept_id",csr.getWorkplaceIds()[1]);
            }else if (csr.getWorkplaceIds().length==3){
                qw.eq("group_id",csr.getWorkplaceIds()[2]);
            }
        }
        //制作等级要求
        qw.eq(csr.getMakeId()!=null&&csr.getMakeId()!=0,"make_id",csr.getMakeId());
        //是否有余额
        if (csr.getBalance()!=null&&csr.getBalance()!=0){
            if (csr.getBalance()==1){
                qw.gt("balance",0);
            }else {
                qw.eq("balance",0);
            }
        }
        //客户等级
        qw.eq(csr.getLevelId()!=null&&csr.getLevelId()!=0,"level_id",csr.getLevelId());
        //消费等级
        qw.eq(csr.getConsumeId()!=null&&csr.getConsumeId()!=0,"consume_id",csr.getConsumeId());

        PageInfo pageInfo = new PageInfo<>(this.baseMapper.selectList(qw));
        System.out.println(pageInfo.getList());
        List<CustomerSelectResponse> list=new ArrayList<>();
        for (Object im: pageInfo.getList()) {
            CustomerSelectResponse cir=new CustomerSelectResponse();
            BeanUtils.copyProperties(im,cir);
            list.add(cir);
        }
        pageInfo.setList(list);
        return Result.success(pageInfo);
    }

    @Override
    public Result findCustomerById(Integer id) {

        Customer customer = this.baseMapper.selectById(id);
        if (customer==null){
            return Result.error();
        }
        CustomerSelectResponse customerSelectResponse=new CustomerSelectResponse();
        BeanUtils.copyProperties(customer,customerSelectResponse);

        return Result.success(customerSelectResponse);
    }

    @Override
    public Result updateCustomer(CustomerAddAndUpdateRequest customerAddAndUpdateRequest) {
        SysUser loginUser = SecurityUtil.getLoginUser();
        Customer customer = new Customer();
        //制作等级
        if (customerAddAndUpdateRequest.getMakeId()!=null&&customerAddAndUpdateRequest.getMakeId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getMakeId());
            customer.setMakeName(byId.getLabel());
            customer.setMakeId(byId.getId());
        }
        //消费等级
        if (customerAddAndUpdateRequest.getConsumeId()!=null&&customerAddAndUpdateRequest.getConsumeId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getConsumeId());
            customer.setConsumeName(byId.getLabel());
            customer.setConsumeId(byId.getId());
        }

        //客户等级
        if (customerAddAndUpdateRequest.getLevelId()!=null&&customerAddAndUpdateRequest.getLevelId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getLevelId());
            customer.setLevelName(byId.getLabel());
            customer.setLevelId(byId.getId());
        }
        //自定义标签
        if (customerAddAndUpdateRequest.getTagId()!=null&&customerAddAndUpdateRequest.getTagId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getTagId());
            customer.setTagName(byId.getLabel());
            customer.setTagId(byId.getId());
        }
        BeanUtils.copyProperties(customerAddAndUpdateRequest,customer);
        customer.setUpdateBy(loginUser.getId());
        customer.setUpdateTime(new Date());
        int insert = this.baseMapper.updateById(customer);
        return Result.success(insert);
    }

    @Override
    public Result addCustomer(CustomerAddAndUpdateRequest customerAddAndUpdateRequest,SysUser sysUser) {
        System.out.println("customerAddAndUpdateRequest = " + customerAddAndUpdateRequest);

        Customer customer = new Customer();
        //制作等级
        if (customerAddAndUpdateRequest.getMakeId()!=null&&customerAddAndUpdateRequest.getMakeId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getMakeId());
            customer.setMakeName(byId.getLabel());
            customer.setMakeId(byId.getId());
        }
        //消费等级
        if (customerAddAndUpdateRequest.getConsumeId()!=null&&customerAddAndUpdateRequest.getConsumeId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getConsumeId());
            customer.setConsumeName(byId.getLabel());
            customer.setConsumeId(byId.getId());
        }

        //客户等级
        if (customerAddAndUpdateRequest.getLevelId()!=null&&customerAddAndUpdateRequest.getLevelId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getLevelId());
            customer.setLevelName(byId.getLabel());
            customer.setLevelId(byId.getId());
        }
        //自定义标签
        if (customerAddAndUpdateRequest.getTagId()!=null&&customerAddAndUpdateRequest.getTagId()!=0){
            SysDictData byId = dds.getById(customerAddAndUpdateRequest.getTagId());
            customer.setTagName(byId.getLabel());
            customer.setTagId(byId.getId());
        }

        Calendar calender = Calendar.getInstance();
        String no="";
        String month=calender.get(Calendar.MONTH)+"";
        if (month.length()==1){
            month="0"+month;
        }
        no+=month;
        String date=calender.get(Calendar.DATE)+"";
        if (date.length()==1){
            date="0"+date;
        }
        no+=date;
        Random r = new Random();
        for (int i=0;i<3;i++){
            // 通过对象方法获取随机数
            int data = r.nextInt(10);
            no+=data;
        }
        //客户编号
        customer.setCustomerNo(no);
        //所属客服
        customer.setServiceId(sysUser.getId());
        customer.setServiceName(sysUser.getName());
        //添加客服所在公司部门小组
        QueryWrapper qw=new QueryWrapper();
        qw.eq("id",sysUser.getDeptId());
        while (true){
            SysDept sysDept = ds.getBaseMapper().selectOne(qw);
            qw=new QueryWrapper();
            if (sysDept.getAncestors().split(",").length==3){
                //客服所在部门
                customer.setDeptId(sysDept.getId());
                customer.setDeptName(sysDept.getName());
                qw.eq("id",sysDept.getParentId());
            }else if (sysDept.getAncestors().split(",").length==2){
                //客服所在公司
                customer.setCompanyId(sysDept.getId());
                customer.setCompanyName(sysDept.getName());
                break;
            }else if (sysDept.getAncestors().split(",").length==4){
                //客服所在小组
                customer.setGroupId(sysDept.getId());
                customer.setGroupName(sysDept.getName());
                qw.eq("id",sysDept.getParentId());
            }
        }
        BeanUtils.copyProperties(customerAddAndUpdateRequest,customer);
        int insert = this.baseMapper.insert(customer);
        return Result.success(insert);
    }


    @Override
    public List<Customer> queryCustomerInfo() {
        return customerMapper.selectList(null);
    }
}
